package cn.by.wms.mybatisx;

import cn.by.wms.entity.BaseEntity;
import cn.by.wms.entity.Warehouse;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.smart.core.util.UserSessionContext;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.sql.PreparedStatement;

@Component
@Intercepts({
        @Signature(type = ParameterHandler.class, method = "setParameters", args = {PreparedStatement.class})
})
public class ParameterPlugin implements Interceptor {

    private static  final  String LAST_UPDATE_BY ="lastUpdateBy";
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        ParameterHandler parameterHandler = (ParameterHandler)invocation.getTarget();
        Object parameterObject = parameterHandler.getParameterObject();
        //方法一：通过反射看看这个对象是否有 这个属性字段  lastUpdateBy
//         Field field = ReflectUtil.getField(parameterObject.getClass(), LAST_UPDATE_BY);
////        // 检查参数对象是否为空
//         if(ObjectUtil.isNotEmpty(field)){
//        String nickName = UserSessionContext.get().getNickName();
//         ReflectUtil.setFieldValue(parameterObject,field,nickName);
//         }
        //方法二：性能高
        if(parameterObject instanceof BaseEntity  && ObjUtil.isNotEmpty(UserSessionContext.get())){
            BaseEntity baseEntity = (BaseEntity) parameterObject;

            String nickName = UserSessionContext.get().getNickName();
            baseEntity.setLastUpdateBy(nickName);
        }

        return invocation.proceed();
    }
}
